import { defineStore } from 'pinia';
import { Notification } from '@arco-design/web-vue';
import type {
  RouteLocationNormalized,
  RouteRecordNormalized,
} from 'vue-router';
import defaultSettings from '@/config/settings.json';
import appClientMenus from '@/router/app-menus';
import { getBaseUrl } from '@/utils/tools';
import tree from '@/utils/tree';
import { AppState } from './types';
import { MenuAuthParam, PortalAuth } from '../user/types';

const useAppStore = defineStore('app', {
  state: (): AppState => ({ ...defaultSettings }),

  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appBaseUrl(state: AppState) {
      return state.baseUrl;
    },
    appActivePortal(state: AppState) {
      return state.activePortal;
    },
    appActivePortalName(state: AppState) {
      return state.activePortalName;
    },
    appAsyncMenus(state: AppState): RouteRecordNormalized[] {
      return state.serverMenu as unknown as RouteRecordNormalized[];
    },
    appServerPortalAuths(state: AppState): PortalAuth[] {
      return state.serverPortalAuths;
    },
    appBreadcrumbList(state: AppState): RouteRecordNormalized[] {
      return state.breadcrumbList;
    },
  },

  actions: {
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial);
    },

    updateActivePortal(portal: PortalAuth) {
      this.activePortal = portal.url;
      this.activePortalName = portal.name;
    },

    generateBreadcrumbList(to: RouteLocationNormalized) {
      this.breadcrumbList = to.matched;
    },

    async getBaseUrl() {
      if (!this.baseUrl) {
        this.baseUrl = await getBaseUrl();
      }
      return this.baseUrl;
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark';
        document.body.setAttribute('arco-theme', 'dark');
      } else {
        this.theme = 'light';
        document.body.removeAttribute('arco-theme');
      }
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
    async initServerMenuConfig(menus: string[]) {
      try {
        if (menus) {
          let authAppModules: any[] = [];
          const localRoute = tree.flatTreeData(appClientMenus);
          const getParams = (params: MenuAuthParam[] | undefined) => {
            const paramsStr = {};
            if (params) {
              params.sort().forEach((item: MenuAuthParam) => {
                // @ts-ignore
                paramsStr[item.paramKey] = item.paramValue;
              });
            }
            return paramsStr;
          };
          appClientMenus.forEach((item) => {
            authAppModules.push({
              name: item.name,
              path: item.path,
              meta: item.meta,
              redirect: item.redirect,
              id: item.name,
              parentId: '',
            });
          });
          menus.forEach((item: string) => {
            localRoute.forEach((iteml: RouteRecordNormalized) => {
              const obj = JSON.parse(JSON.stringify(iteml));
              if (item === obj.name) {
                authAppModules.push({
                  ...obj,
                  id: obj.name,
                  parentId: obj.meta.parentId,
                });
              }
            });
          });
          authAppModules = tree.toTree(authAppModules, 'id', 'parentId');
          authAppModules = authAppModules.filter((item) => item.children);
          this.serverMenu = [
            ...(appClientMenus.filter(
              (item) =>
                (item.name as unknown as string) === 'dashboard' ||
                (item.name as unknown as string) === 'redirectWrapper'
            ) as unknown as RouteRecordNormalized[]),
            ...authAppModules,
          ];
          // Notification.success({
          //   id: 'menuNotice',
          //   content: `切换门户菜单到${defaultPortal.name}成功`,
          //   closable: true,
          // });
        }
      } catch (error) {
        Notification.error({
          id: 'menuNotice',
          content: '初始化门户菜单失败！',
          closable: true,
        });
      }
    },
    clearServerMenu() {
      this.serverMenu = [];
    },
  },
});

export default useAppStore;
